﻿Imports System.Runtime.CompilerServices

''' <summary>
''' Предоставляет методы расширения для визуализации списка архива с разделением по годам.
''' </summary>
Public Module YearListHtmlHelper

    <Extension()>
    Public Function YearList(base As HtmlHelper, years As IEnumerable(Of Integer), htmlAttributes As Object) As MvcHtmlString
        If years IsNot Nothing AndAlso Not years.Any Then Return MvcHtmlString.Empty

        Dim currentYear As Integer = 0
        If HttpContext.Current.Request.RequestContext.RouteData.Values.ContainsKey("id") Then
            Integer.TryParse(HttpContext.Current.Request.RequestContext.RouteData.GetRequiredString("id"), currentYear)
        End If

        Dim ul As New TagBuilder("ul")

        With ul
            .MergeAttributes(New RouteValueDictionary(htmlAttributes))

            For Each item In years
                .InnerHtml += BuildLi(item, currentYear)
            Next
        End With

        Return MvcHtmlString.Create(ul.ToString(TagRenderMode.Normal))
    End Function

#Region "Вспомогательные методы"

    Private Function BuildLi(year As Integer, currentYear As Integer) As String
        Dim li As New TagBuilder("li")
        Dim href As String = String.Empty

        With li
            If currentYear = year Then
                .AddCssClass("disabled")
            Else
                .Attributes.Add("title", String.Format("Архив новостей за {0} год", year))
                href = VirtualPathUtility.ToAbsolute(String.Format("~/news/archive/year/{0}", year))
            End If
            .InnerHtml = BuildA(href, year)
        End With

        Return li.ToString(TagRenderMode.Normal)
    End Function

    Private Function BuildA(href As String, text As String) As String
        Dim a As New TagBuilder("a")

        With a
            If Not String.IsNullOrEmpty(href) Then .Attributes.Add("href", href)
            .InnerHtml = text
        End With

        Return a.ToString(TagRenderMode.Normal)
    End Function

#End Region

End Module
